//
//  WmcPhotoPreviewVM.swift
//  YPWatermarkCamera
//
//  Created by 周诗松 on 2022/4/15.
//

import Foundation
import RxRelay
import UIKit
import YPBedrock
import YPGraphicEngine

class WmcPhotoPreviewVM: WmcBaseVM {
    // MARK: 入参

    /// 水印照片
    var watermarkPhoto: UIImage?

    /// 标准照片
    var standardPhoto: UIImage?
    
    /// 二维码图片
    var qrImage: UIImage?

    /// 画幅比
    var aspectRatio: YPGESunglasses.AspectRatio = .ar_4_3

    /// 水印模型
    var watermarkModel: WmcWatermarkDetailModel?

    /// 水印中心点坐标
    var watermarkCenterPoint: CGPoint?

    // MARK: 输出

    /// 加载的图片
    let loadPreviewImageRelay: BehaviorRelay<UIImage?> = .init(value: nil)

    /// 水印是否可编辑
    let watermarkInteractionEnabledRelay: PublishRelay<Bool> = .init()

    /// 水印切换
    let loadWatermarkRelay: BehaviorRelay<WmcWatermarkDetailModel> = .init(value: .init())

    /// 画幅比改变
    let aspectRatioRelay: PublishRelay<YPGESunglasses.AspectRatio> = .init()

    /// 图片处理完成
    var photoFinishRelay: BehaviorRelay<YPWmcManager.PhotoResult?> = .init(value: nil)

    // MARK: 回调

    /// 点击存相册回调
    var saveAlbumBlock: YPBlock.FourParam<UIImage, UIImage, WmcWatermarkDetailModel, UIImage?>?

    /// 点击保存后返回回调
    var saveBackBlock: YPBlock.Empty?

    /// 点击重拍后返回回调
    var retakeBackBlock: YPBlock.Empty?

    // MARK: 其他

    /// 水印是否可编辑
    var isWatermarkInteractionEnabled: Bool = true

    /// 当前的标准图片
    var currentStandardImage: UIImage?

    /// 代理获取，减少代码长度
    var photoPreviewDelegate: WmcPhotoPreviewDelegate? {
        return YPWmcManager.shared.uiDelegate.photoPreviewDelegate
    }
    
    /// 是否显示二维码
    var showQRCode: Bool {
        return qrImage != nil
    }

    // MARK: 输入

    /// 加载预览图
    func loadPreviewImage() {
        // 水印可否编辑
        if let _isWatermarkInteractionEnabled = photoPreviewDelegate?.watermarkInteractionEnabled(.current) {
            isWatermarkInteractionEnabled = _isWatermarkInteractionEnabled
        }
        if isWatermarkInteractionEnabled { // 可编辑
            // 加载标准原图
            currentStandardImage = standardPhoto
            // 加载水印
            if let watermarkModel = watermarkModel {
                setWatermarkModel(watermarkModel)
            }
        } else { // 不可编辑
            currentStandardImage = watermarkPhoto
        }
        // 回调使用图片
        loadPreviewImageRelay.accept(currentStandardImage)
        // 输出编辑状态
        watermarkInteractionEnabledRelay.accept(isWatermarkInteractionEnabled)
        // 加载画幅比UI
        aspectRatioRelay.accept(aspectRatio)
    }

    /// 设置水印（带拷贝）
    func setWatermarkModel(_ model: WmcWatermarkDetailModel) {
        loadWatermarkRelay.accept(model)
    }

    /// 合成图片
    func fotoMix(watermarkContentView: WmcWatermarkContentView, qrcodeView: WmcQRCodeVerifyView?) {
        if isWatermarkInteractionEnabled {
            guard let standardPhoto = standardPhoto else { return }
            guard let contentWatermarkModel = watermarkContentView.watermarkModel else { return }
            // 显示官方水印
            if contentWatermarkModel.templateId != 0, // 不是无水印
               !WmcPreferenceSettingsManager.shared.cameraSetting.hiddenOfficialMark
            { // 没隐藏官水印
                watermarkContentView.showOfficialWatermark()
            }
            var screenshotScale = UIScreen.main.scale
            if standardPhoto.size.width > standardPhoto.size.height {
                screenshotScale *= 4
            }
            
            guard let watermarkImage = watermarkContentView.yp.screenshot(scale: screenshotScale) else { return }
            // 隐藏官方水印
            watermarkContentView.hideOfficialWatermark()
            // 水印叠加
            var qrVerImage: UIImage?
            if showQRCode {
                qrVerImage = WmcWatermarkUtil.makeQRImageResult(with: contentWatermarkModel, qrcodeView: qrcodeView).qrVerImage
            }
            let drawWatermarkImage = WmcWatermarkUtil.makeImage(standardImage: standardPhoto, watermarkImage: watermarkImage, qrVerImage: qrVerImage)
            // 生成带水印的标准图片
            guard let watermarkPhoto = drawWatermarkImage,
                  let watermarkModel = watermarkContentView.watermarkModel else { return }
            // 标记记录地点
            watermarkModel.createLocationInfo()
            // 图片处理完回调
            photoFinishRelay.accept((watermarkPhoto, standardPhoto, watermarkModel, qrImage))
        } else {
            // 直接返回传入的图片
            guard let watermarkPhoto = watermarkPhoto,
                  let standardPhoto = standardPhoto,
                  let watermarkModel = watermarkModel else { return }
            // 标记记录地点
            watermarkModel.createLocationInfo()
            // 图片处理完回调
            photoFinishRelay.accept((watermarkPhoto, standardPhoto, watermarkModel, qrImage))
        }
    }

    /// 保存相册
    func saveAlbum(_ result: YPWmcManager.PhotoResult) {
        saveAlbumBlock?(result.0, result.1, result.2, result.3)
    }

    /// 回调保存返回
    func saveBack() {
        saveBackBlock?()
    }

    /// 重拍
    func retakeBack() {
        retakeBackBlock?()
    }

    /// 分享朋友圈
    func shareFriendCircle() {
        guard let value = photoFinishRelay.value else { return }
        WmcShareManager.shareImage(value.0, scene: .friendCircle)
    }

    /// 分享微信
    func shareWechat() {
        guard let value = photoFinishRelay.value else { return }
        WmcShareManager.shareImage(value.0, scene: .session)
    }
}
